package dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import utils.DbUtil;

import dao.AuthDao;
import entity.Auth;

public class AuthDaoImpl implements AuthDao {

	public List<Auth> getAuthList() throws SQLException {
		return DbUtil.queryRunner().query("select * from j_auth where 1 order by `sort` asc", new BeanListHandler<Auth>(Auth.class));
	}

	public int updateStatus(int id, int status) throws SQLException {
		Object[] params = {status, id};
		return DbUtil.queryRunner().update("update j_auth set `status`=? where id=?", params);
	}

	@SuppressWarnings("deprecation")
	public int judgeHasChildByParentId(int id) throws SQLException {
		long result = DbUtil.queryRunner().query("select count(*) from j_auth where parent_id=?", id, new ScalarHandler<Long>());
		return (int) result;
	}

	public int deleteAuthById(int id) throws SQLException {
		return DbUtil.queryRunner().update("delete from j_auth where id=?", id);
	}

	public int updateMenu(int id, int is_menu) throws SQLException {
		Object[] params = {is_menu, id};
		return DbUtil.queryRunner().update("update j_auth set is_menu=? where id=?", params);
	}

	public int addAth(Auth auth) throws SQLException {
		Object[] params = {auth.getName(), auth.getUrl(), auth.getParent_id(),auth.getSort(),auth.getStatus(),auth.getIs_menu(),auth.getDate_entered()};
		return DbUtil.queryRunner().update("insert into j_auth (name,url,parent_id,`sort`,`status`,is_menu, date_entered) values (?,?,?,?,?,?,?)", params);
	}

	@SuppressWarnings("deprecation")
	public Auth getAuthById(int id) throws SQLException {
		return DbUtil.queryRunner().query("select * from j_auth where id=?", id, new BeanHandler<Auth>(Auth.class));
	}

	public int editAuth(Auth auth) throws SQLException {
		Object[] params = {auth.getName(), auth.getUrl(), auth.getParent_id(),auth.getSort(),auth.getStatus(),auth.getIs_menu(),auth.getId()};
		return DbUtil.queryRunner().update("update j_auth set name=?,url=?, parent_id=?,`sort`=?,`status`=?,is_menu=? where id=?", params);
	}

	@SuppressWarnings("deprecation")
	public List<Auth> getAdminAuth(String auth) throws SQLException {
		return DbUtil.queryRunner().query("select * from j_auth where id in ("+auth+")", null, new BeanListHandler<Auth>(Auth.class));
	}

	public List<Auth> getMenuList() throws SQLException {
		return DbUtil.queryRunner().query("select * from j_auth where is_menu=1 and `status`=1 order by `sort` asc", new BeanListHandler<Auth>(Auth.class));
	}

	public List<Auth> getRoleAuthList() throws SQLException {
		return DbUtil.queryRunner().query("select * from j_auth where `status`=1 order by `sort` asc", new BeanListHandler<Auth>(Auth.class));
	}

}
